package com.hqu.environment.resolver;

import com.hqu.environment.annotation.LoginUser;
import com.hqu.environment.constant.Constant;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * @Description: resolver:  自定义参数解析器用于将解析的token获取用户id，
 *          注入到带有@LoginAdmin的参数中去
 * @Author: 邓勇嘉
 * @Date:2018/11/19 18:12
 * */


public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    /*
     * 当遇到@LoginAdmin Integer 形式执行参数解析方法
     * */
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(Integer.class) && parameter.hasParameterAnnotation(LoginUser.class);
    }

    /*
     * 获取request中的id注入到参数中
     * */
    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        Object object = webRequest.getAttribute(Constant.LOGIN_USER, RequestAttributes.SCOPE_REQUEST);

        Integer userId =Integer.parseInt(object.toString());

        return userId;
    }
}
